/*
 * Copyright 1999-2018 Alibaba Group Holding Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.alibaba.csp.sentinel.dashboard.rule.nacos.authority;

import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.AuthorityRuleEntity;
import com.alibaba.csp.sentinel.dashboard.rule.DynamicRuleProvider;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRule;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.config.ConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Eric Zhao
 * @since 1.4.0
 */
@Component("authorityRuleNacosProvider")
public class AuthorityRuleNacosProvider implements DynamicRuleProvider<List<AuthorityRuleEntity>> {

    @Autowired
    private ConfigService configService;

    @Value("${sentinel.nacos.authority_data_id_postfix}")
    private String nacosAuthorityDataIdPostFix;

    @Value("${sentinel.nacos.group_id}")
    private String nacosGroupId;

    @Override
    public List<AuthorityRuleEntity> getRules(String appName) throws Exception {
        String rules = configService.getConfig(appName + nacosAuthorityDataIdPostFix,
                nacosGroupId, 3000);
        if (StringUtil.isEmpty(rules)) {
            return new ArrayList<>();
        }

        List<InnerAuthority> innerAuthorities = JSON.parseArray(rules, InnerAuthority.class);
        List<AuthorityRuleEntity> authorityRuleEntities =new ArrayList<>();
        for(InnerAuthority innerAuthority:innerAuthorities) {
            AuthorityRuleEntity authorityRuleEntity = new AuthorityRuleEntity();
            AuthorityRule authorityRule = new AuthorityRule();
            authorityRule.setLimitApp(innerAuthority.getLimitApp());
            authorityRule.setResource(innerAuthority.getResource());
            authorityRule.setStrategy(innerAuthority.getStrategy());
            authorityRuleEntity.setRule(authorityRule);
            authorityRuleEntities.add(authorityRuleEntity);
        }
        return authorityRuleEntities;
    }
}
